<template>
 <div>
   <h5>多表单同时验证</h5>
   <div>
       <el-button type="primary" @click="submitForm(false)">提交</el-button>
   </div>
   <el-form :model="ruleForm" :rules="rules" ref="ruleForm1" label-width="100px" >
     <el-form-item label="活动名称" prop="name">
       <el-input v-model="ruleForm.name"></el-input>
     </el-form-item>
   </el-form>

   <el-form :model="ruleForm" :rules="rules" ref="ruleForm2" label-width="100px">
     <el-form-item label="活动形式" prop="desc">
       <el-input type="textarea" v-model="ruleForm.desc"></el-input>
     </el-form-item>
   </el-form>

   <el-form ref="queryContextForm" :model="queryContext" :rules="queryContextRules" :show-message="false" class="szhbd" label-position="top" status-icon>
         <el-form-item label="工程名称" prop="projectName">
           <el-input v-model="queryContext.projectName" disabled></el-input>
         </el-form-item>
   </el-form>
   <h5>js中 数组和Object的keys(),values()和entries()方法<br/>
     它们都返回一个遍历器对象，可以用for…of循环进行遍历，区别是keys()是对键名的遍历、values()是对键值的遍历，entries()是对键值对的遍历.</h5>
   <el-button type="primary" @click="useFun">测试js方法的使用方法</el-button>

   <h5 class="mt-1">表格编辑行</h5>
   <avue-crud ref="crud" :option="rowEditTableoption" :data="rowEditTabledata" @row-update="addUpdate" @row-save="rowSave"  >

   </avue-crud>

   <div style="margin-top: 10px"></div>
   <el-button @click="changePermission" >computed验证</el-button>
   <el-button type="text" v-if="permissionList('gcxm_HSE_ConstructionRegist_del')">删除</el-button>
   <el-button type="text" v-if="permissionList2['addBtn']">删除</el-button>

   <div style="margin-top: 10px"></div>
   <el-button type="primary" @click="showDialog">弹框</el-button>

   <div style="margin-top: 10px"></div>
   <div class="block">
     <span class="demonstration">默认 click 触发子菜单</span>
     <el-cascader
         v-model="selectValues"
         :options="selectOptions"
         :props="{ multiple: true, value: 'value', label: 'label' }"
         @change="selectHandleChange"></el-cascader>

     <el-button @click="setSelectVals">给节点赋值</el-button>
   </div>

   <div style="margin-top: 10px"></div>
   <div class="block">
     <span class="demonstration">防抖</span>
     <el-button type="primary" @click="debounceNodeClick">防止反复提交</el-button>
   </div>

   <Dialog ref="Dialog"></Dialog>

   <el-button @click="showTipCom">展示自定义提示组件</el-button>

   <el-button @click="showLowCode">json数据</el-button>

   <div v-for="(value,key) in commonProps">
      {{value}} **** {{key}}
   </div>


   <el-button @click="testRxg">正则截取</el-button>
   <el-button @click="formatTableData">处理数据</el-button>
 </div>
</template>


<script>
import {dateFormat} from '@/utils/date'
import Dialog from "@/components/keySummary/components/dialog";
import {showTip} from "@/components/keySummary/components/testDialog/index"

import {COMMON_PROPERTIES} from './data'
/**
 *  this.$refs.crud.searchReset(); 清空搜索栏
 *  tableOption:{
          refreshBtn: false,
          addBtn: false,
          delBtn:false,
          columnBtn: false,
          searchBtn: false,
          gridBtn:false,
     }
 */
    import {mapGetters} from "vuex"
    import debounce from 'throttle-debounce/debounce';
    import {openFormDialog} from "@/components/keySummary/components/myPublicDialog/index"
import dataJson from './data'
    export default {
      components:{
        Dialog
      },
      computed:{
        ...mapGetters([ "storeNum","permission"]),
        permissionList() { //第一种
          return (code) => {
            return this.vaildData(this.permission[code], false)
          }
        },
        permissionList2() {//第一种
          return {
            addBtn:this.vaildData(this.permission['gcxm_HSE_ConstructionRegist_del'], false),
          }
        }
      },
      created() {
        console.log("********",this.$store.state.permission)


      },
      data() {
        const validatePass = (rule, value, callback) => {
          if (this.isShow[rule.field].required) {
            if (!this.queryContext[rule.field] || this.queryContext[rule.field] === '') {
              const msg = {
                divideId: "请选择单项工程",
                unitId: "请选择单位工程",
                divisionalId: "请选择分部工程",
                subProjectsId: "请选择分项工程",
                inspectionBatchId: "请选择检验批工程"
              }
              callback(new Error(msg[rule.field]));
            }
          }
          callback();
        };
        return {
          ruleForm: {
            name: '',
            desc:''
          },
          rules: {
            name: [
              { required: true, message: '请输入活动名称', trigger: 'blur' },
              { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
            ],
            desc: [
              { required: true, message: '请输入活动名称', trigger: 'blur' },
            ],
          },
          queryContext: {
            divideId: "",
            unitId: "",
            divisionalId: "",
            subProjectsId: "",
            inspectionBatchId: "",
          },
          queryContextRules: {
            divideId: [{validator: validatePass, trigger: 'change'}],
            unitId: [{validator: validatePass, trigger: 'change'}],
            divisionalId: [{validator: validatePass, trigger: 'change'}],
            subProjectsId: [{validator: validatePass, trigger: 'change'}],
            inspectionBatchId: [{validator: validatePass, trigger: 'change'}],
            projectSupervisor: [{validator: validatePass, trigger: 'change'}]
          },
          rowEditTableoption:{
            addBtn:true,
            addBtnText:'新增表单',
            editBtn:true,
            addRowBtn:true,
            cellBtn:true,
            cancelBtn:true,
            column: [
              {
                label:'范围日期设置日期value的格式字符串非数组',
                prop: 'rangeDate',
                cell: true,
                type: 'daterange', //timerange daterange
                format:'yyyy-MM-dd', //HH:mm:ss
                valueFormat:'yyyy-MM-dd',
                startPlaceholder: '时间开始范围自定义',
                endPlaceholder: '时间结束范围自定义',
                dataType: "string", // （重要配置）将返回值由数组改为逗号分开的string
                searchOrder: "2", //	搜索项位置排序，序号越大越靠前
                rangeSeparator: "至",
              },
              {
              label:'姓名',
              prop: 'name',
              cell: true,
              rules: [
                {
                  required: true,
                  message: '请输入姓名',
                  trigger: 'blur'
                }
              ]
            },{
              label:'性别',
              prop: 'sex',
              type:'select',
              dicData:[{
                label:'男',
                value:0
              },{
                label:'女',
                value:1
              }],
              cell: true
            },{
              label:'开关',
              prop: 'switch',
              type:'switch',
              cell: true
            }]
          },
          rowEditTabledata:[{}],
          selectValues: [["zhinan1"],'zhinan2'],
          selectOptions: [ {
            value: 1,
            label: '东南',
            children: [
              {
                value: 11,
                label: '上海',
                children: [{
                  value: 111,
                  label: '黄浦区'
                }, {
                  value: 112,
                  label: '静安区'
                }, {
                  value: 113,
                  label: '虹口区'
                }, {
                  value: 114,
                  label: '长宁区'
                }]
              }, {
                value: 12,
                label: '江苏',
              }, {
                value: 13,
                label: '浙江',
              }
            ]
          },
            {
              value: 2,
              label: '西北',
              children: [{
                value: 21,
                label: '陕西',
              }, {
                value: 22,
                label: '新疆维吾尔族自治区',
              }]
            },
            {
              value: 3,
              label: '大西北',
            },{
              value: 4,
              label: '大西南',
            }],
          debounceNodeClick: debounce(500, this.clickRepeat),
          data:dataJson,
          commonProps:COMMON_PROPERTIES,
          form: {
            curWeekTableOne:[{xfdw:'我是下发单位',bzjsxs:'',bzzgxs:'',wwcyy:'',jswcss:'',bz:''},
              {xfdw:'我是下发单位',bzjsxs:'',bzzgxs:'',wwcyy:'',jswcss:'',bz:''}, {xfdw:'我是下发单位22',bzjsxs:'',bzzgxs:'',wwcyy:'',jswcss:'',bz:''}]
          }
        };
      },
      methods: {
        async submitForm() {
            let res = await Promise.all([this.validateForm('ruleForm1'),this.validateForm('ruleForm2')]) ;
            console.log("--------res:",res) //[false,false]
            let flag =  res.every(item => item)
          console.log("-----flag:",flag)
        },
        validateForm(formRef){
          return  new Promise((resolve,rejecrt) => {
            this.$refs[formRef].validate((valid)=>{
                      console.log("valid:",valid)
                      resolve(valid)
                    })
                 })
        },
        useFun(){
          let arr = ['a', 'b', 'c']
          for (let index of arr.keys()) {
            console.log(index); //0 1 2
          }

          for (let item of arr.values()) {
            console.log(item); //  a b c
          }

          for (let [index, item] of arr.entries()) {
            console.log(index, item); // 0 'a'  1 'b'  2 'c'
          }


          let obj = {
            name:"张三",
            sex:"男",
            age:20
          }

          for ( let key of Object.keys(obj)){
            console.log(key)
          }
          // name
          // sex
          // age
          for ( let val of Object.values(obj)){
            console.log(val)
          }
          // 张三
          // 男
          // 20

          for ( let val of Object.entries(obj)){
            console.log(val)
          }
          // (2) ["name", "张三"]
          // (2) ["sex", "男"]
          // (2) ["age", 20]
          for ( let [key,val] of Object.entries(obj)){
            console.log(key,val)
          }
        // name 张三
        // sex 男
        // age 20
        },
        addUpdate(row,index,done,loading){
          console.log("保存-----row:",row)
          row.id = 1
          done()
          loading()
        },
        rowSave(row,done){
          console.log("更新-----row:",row)
          done()
        },
        changePermission(){
          this.$store.commit('SET_PERMISSION',false) ;
        },
        showDialog(){
          openFormDialog({
            row: {taskId:'11111111111',processInsId:'222222222222'},
            props: {
              title: "流转信息111",
              'close-on-click-modal':false,
              beforeClose(done) {
                done()
              }
            },
            events: {
              close() {

              },
              cancel() {

              },
              confirm(form) {
                console.log("/////////:",form)
              }
            }
          })
          // return new Promise((resolve,reject)=>{
          //    this.$refs.Dialog.init(resolve,reject)
          // })
        },
        selectHandleChange(val){
          console.log("val:",val)
          let vv = JSON.stringify(val)
          let json = JSON.parse(vv)
          console.log("json:",json) ;
        },
        /*
        * @param  list 数据列表
        * @param  id 后端返回的id
        **/
        getParentsById(list, id) {
          for (let i in list) {
            if (list[i].value == id) {
              //查询到就返回该数组对象的value
              return [list[i].value]
            }
            if (list[i].children) {
              let node = this.getParentsById(list[i].children, id)
              if (node !== undefined) {
                //查询到把父节把父节点加到数组前面
                node.unshift(list[i].value)
                return node
              }
            }
          }
        },
        setSelectVals(){
          let data = {depart_id :  "3 ,4"}
          let _depart_check = data.depart_id ? data.depart_id.split(",").map(i => Number(i)) : []
          let _arr = []
// 使用上面写的方法 getParentsById 找出父级id并组合
          _depart_check && _depart_check.map(i => _arr.push(this.getParentsById(this.selectOptions, i)))
          console.log("_arr: ",_arr)
          this.selectValues = _arr

          let a = '111111'
          console.log("a.split(','):",a.split(','))
        },
        async  clickRepeat(){
           let res = await this.showDialog() ;
          console.log("res:",res)

          console.log("日期:",dateFormat(new Date(),'yyyy-MM-dd'))

        },
        showTipCom(){
          showTip({
            tipText: '测试提示信息'
          })
        },
        showLowCode(){
          let strJson = this.data.data.layoutJson ;
          console.log(JSON.parse(strJson))
        },
        testRxg(){

          let str ="http://11.54.87.131:9000/epm-dev/upload/20250208/cd1e603014740942c9438238378f408f.png" ;
          let url =  str.replace(/\/\//g, "")
          let index = url.indexOf('/');
          if (index !== -1) {
            let result = url.substring(index); // 或者使用 str.slice(index + 1);
            console.log(result); // 输出：一个示例字符串
          }
        },
        formatTableData(){
          // const uniqueCategories = new Set(this.form.curWeekTableOne.map(item => item.xfdw));
          // let uniqueDxgcs =  Array.from(uniqueCategories)
          // console.log(uniqueDxgcs); // 输出: ['electronics', 'books', 'clothing']
          // let obj = {}
          // uniqueDxgcs.map(xfdw=>{
          //   this.form.curWeekTableOne.map(item=>{
          //       if (item.xfdw == xfdw){
          //         obj[xfdw].push(item) ;
          //       }
          //   })
          // })
          // console.log("---obj:",obj)

          let formatData = this.groupById(this.form.curWeekTableOne,'xfdw') //分堆
          let arr = []
          for (let i in formatData){
            let a = [{xfdw:i,spanCol:true},...formatData[i]]
            arr.push(...a)
          }
          console.log("arr:",arr)
        },
        groupById(arr, idKey) {
          return arr.reduce((acc, obj) => {
            const id = obj[idKey];
            if (!acc[id]) acc[id] = [];
            acc[id].push(obj);
            return acc;
          }, {});
        },

      }
    }
  </script>

<style scoped>
.title{margin-top: 10px;background: #FFFFFF;text-align: left;color: #000}
</style>